package com.zadetk.helpyou.activities;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.UiSettings;
import com.amap.api.maps2d.model.MyLocationStyle;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.iarcuschin.simpleratingbar.SimpleRatingBar;
import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.RecognizerListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechRecognizer;
import com.iflytek.cloud.SpeechUtility;
import com.zadetk.helpyou.App;
import com.zadetk.helpyou.R;
import com.zadetk.helpyou.adapter.MyAdapter;
import com.zadetk.helpyou.base.AbsActivity;
import com.zadetk.helpyou.bean.VoiceBean;
import com.zadetk.helpyou.utils.LogUtil;
import com.zadetk.helpyou.utils.ToastUtil;
import com.zadetk.helpyou.view.NoScrollView;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import pl.droidsonroids.gif.GifImageView;

import static android.Manifest.permission.ACCESS_COARSE_LOCATION;
import static android.Manifest.permission.READ_PHONE_STATE;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;

/**
 * 8-1语音页面
 */
public class VoiceActivity extends AbsActivity implements View.OnClickListener {
    private GifImageView gifBtn;
    private SpeechRecognizer mIat;
    private RecognizerListener mRecognizerListener;
    private int ret;
    private TextView tvVoiceContent;
    private RecyclerView recycleview;
    private RecyclerView recycleview2;
    private VoiceAdpater voiceAdpater;
    private ViewFlipper viewFlipper;
    private List<VoiceBean> data = new LinkedList<>();
    private List<VoiceBean> data2 = new LinkedList<>();
    private Voice2Adpater voice2Adpater;
    private TextView tvTitle;
    private TextView tvName;
    private TextView tvDec1;
    private TextView tvEvaluateNum;
    private SimpleRatingBar rbMark;
    private TextView tvPrice;
    private MapView map;
    private TextView vBtnCall;
    private TextView vBtnMessage;
    private TextView vAddress;
    private ImageView ivImg;
    private TextView tvBtnReservation;

    private String[] per = {ACCESS_COARSE_LOCATION, WRITE_EXTERNAL_STORAGE, READ_PHONE_STATE};
    private AMap aMap;
    private MyLocationStyle myLocationStyle;

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        map.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行map.onResume ()，重新绘制加载地图
        map.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行map.onPause ()，暂停地图的绘制
        map.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行map.onSaveInstanceState (outState)，保存地图当前的状态
        map.onSaveInstanceState(outState);
    }

    @Override
    public void onBackPressed() {
        if (viewFlipper.getDisplayedChild() == 0) {
            super.onBackPressed();
        } else {
            viewFlipper.showPrevious();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        mIat.stopListening();
    }

    @Override
    public int getStatusBarColor() {
        return R.color.transparent;
    }

    @Override
    public boolean isfit() {
        return false;
    }

    @Override
    public LinearLayout initToolbar(ViewGroup parent) {
        return null;
    }

    @Override
    public int setView() {
        return R.layout.activity_voice;
    }

    @Override
    public void initBasic(Bundle savedInstanceState) {
        initViews();
        initLogic();
        map.onCreate(savedInstanceState);
        requestData();
    }

    private void requestData() {
        VoiceBean voiceBean = new VoiceBean();
        data.add(voiceBean);
        data.add(voiceBean);
        data.add(voiceBean);
        data.add(voiceBean);
        data.add(voiceBean);
        voiceAdpater.notifyDataSetChanged();
        data2.add(voiceBean);
        data2.add(voiceBean);
        data2.add(voiceBean);
        voice2Adpater.notifyDataSetChanged();
    }

    private void initLogic() {
        initSpeech();
        voiceAdpater = new VoiceAdpater(R.layout.voice_item, data);
        recycleview.setAdapter(voiceAdpater);
        View v = getLayoutInflater().inflate(R.layout.voice_header, null);
        voiceAdpater.addHeaderView(v);
        startListen();
        gifBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startListen();
                tvVoiceContent.setText("正在倾听...");
                tvTitle.setVisibility(View.GONE);
                recycleview.setVisibility(View.GONE);
                if (viewFlipper.getDisplayedChild() == 1) {
                    viewFlipper.showPrevious();
                }
            }
        });
        voiceAdpater.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                viewFlipper.showNext();
            }
        });

        voice2Adpater = new Voice2Adpater(R.layout.voice_item2, data2);
        View v2 = getHeaderView2();
        voice2Adpater.addHeaderView(v2);
        recycleview2.setAdapter(voice2Adpater);
        vBtnCall.setOnClickListener(this);
        vBtnMessage.setOnClickListener(this);
    }

    private View getHeaderView2() {
        View v = getLayoutInflater().inflate(R.layout.voice_header2, null);
        tvTitle = v.findViewById(R.id.tv_title);
        tvName = v.findViewById(R.id.tv_name);
        tvDec1 = v.findViewById(R.id.tv_dec1);
        tvEvaluateNum = v.findViewById(R.id.tv_evaluate_num);
        rbMark = v.findViewById(R.id.rb_mark);
        tvPrice = v.findViewById(R.id.tv_price);
        map = v.findViewById(R.id.map);
        vBtnCall = v.findViewById(R.id.v_btn_call);
        vBtnMessage = v.findViewById(R.id.v_btn_message);
        vAddress = v.findViewById(R.id.v_address);
        ivImg = v.findViewById(R.id.iv_img);
        tvBtnReservation = v.findViewById(R.id.tv_btn_reservation);
        performCodeWithPermission("需要定位权限", new PermissionCallback() {
            @Override
            public void hasPermission() {
                setupMap();
            }

            @Override
            public void noPermission() {

            }
        }, per);
        return v;
    }


    private void setupMap() {
        if (aMap == null) {
            aMap = map.getMap();
        }
        myLocationStyle = new MyLocationStyle();//初始化定位蓝点样式类myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);//连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。（1秒1次定位）如果不设置myLocationType，默认也会执行此种模式。
        myLocationStyle.interval(2000); //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_FOLLOW);//定位一次，且将视角移动到地图中心点。
        aMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
        aMap.setMyLocationEnabled(true);// 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。
        UiSettings uiSet = aMap.getUiSettings();
        uiSet.setZoomControlsEnabled(false);
    }

    private void initViews() {
        gifBtn = findViewById(R.id.gif2);
        tvVoiceContent = findViewById(R.id.tv_voice_content);
        tvTitle = findViewById(R.id.tv_title);
        recycleview = findViewById(R.id.recycleview);
        recycleview2 = findViewById(R.id.recycleview2);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recycleview.setLayoutManager(linearLayoutManager);
        LinearLayoutManager linearLayoutManager2 = new LinearLayoutManager(this);
        linearLayoutManager2.setOrientation(LinearLayoutManager.VERTICAL);
        recycleview2.setLayoutManager(linearLayoutManager2);
        tvVoiceContent.setText("");
        tvTitle.setVisibility(View.GONE);
        recycleview.setVisibility(View.GONE);
        viewFlipper = findViewById(R.id.viewflipper);
        viewFlipper.setInAnimation(this, R.anim.push_pic_left_in);
        viewFlipper.setOutAnimation(this, R.anim.push_pic_right_out);

    }


    private void initSpeech() {
        SpeechUtility.createUtility(this, SpeechConstant.APPID + "=5af79bed");
        mIat = SpeechRecognizer.createRecognizer(VoiceActivity.this, null);
        mRecognizerListener = new RecognizerListener() {

            @Override
            public void onBeginOfSpeech() {
                LogUtil.d("onBeginOfSpeech");
            }

            @Override
            public void onError(SpeechError error) {
                LogUtil.d("onError" + error.getErrorDescription());
                ToastUtil.showToast("你好像没有说话哦！");
                tvVoiceContent.setText("你好像没有说话哦！");
                //FIXME 测试代码
                tvVoiceContent.setText("这是程序测试内容，请在发布前删除");
                tvTitle.setVisibility(View.VISIBLE);
                recycleview.setVisibility(View.VISIBLE);

            }

            @Override
            public void onEndOfSpeech() {
                LogUtil.d("onEndOfSpeech");
            }

            @Override
            public void onResult(RecognizerResult results, boolean isLast) {
                String result = printResult(results);
                if (TextUtils.isEmpty(result)) {
                    return;
                }
                tvVoiceContent.setText(result);
                tvTitle.setVisibility(View.VISIBLE);
                recycleview.setVisibility(View.VISIBLE);
//                if (isLast) {
//                }
            }

            @Override
            public void onVolumeChanged(int volume, byte[] data) {
            }

            @Override
            public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {

            }
        };
        mIat.setParameter(SpeechConstant.PARAMS, null);

        // 设置听写引擎
        mIat.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD);
        // 设置返回结果格式
        mIat.setParameter(SpeechConstant.RESULT_TYPE, "json");

        // 设置语言
        mIat.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
        // 设置语言区域
        mIat.setParameter(SpeechConstant.ACCENT, "mandarin");
        mIat.setParameter(SpeechConstant.ASR_PTT, "0");
    }

    public String parseVoice(String resultString) {
        Gson gson = new Gson();
        Voice voiceBean = gson.fromJson(resultString, Voice.class);

        StringBuilder sb = new StringBuilder();
        ArrayList<Voice.WSBean> ws = voiceBean.ws;
        for (Voice.WSBean wsBean : ws) {
            String word = wsBean.cw.get(0).w;
            sb.append(word);
        }
        return sb.toString();
    }

    private String printResult(RecognizerResult results) {
        String text = parseVoice(results.getResultString());
        ToastUtil.showToast(text);
        return text;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.v_btn_call:
                call("13708079634");
                break;
            case R.id.v_btn_message:
                final String target = "testpro2"; //消息接收者ID
                final String appkey = "23015524"; //消息接收者appKey
                Intent intent = App.mIMKit.getChattingActivityIntent(target, appkey);
                startActivity(intent);
                break;
        }
    }

    private void call(final String phoneNumber) {
        performCodeWithPermission("拨打电话的权限", new PermissionCallback() {
            @Override
            public void hasPermission() {
                Uri uri = Uri.parse("tel:" + phoneNumber);
                Intent intent = new Intent(Intent.ACTION_CALL, uri);
                startActivity(intent);
            }

            @Override
            public void noPermission() {
            }
        }, Manifest.permission.CALL_PHONE);
    }

    private void startListen() {
        performCodeWithPermission("需要语音权限", new PermissionCallback() {
            @Override
            public void hasPermission() {
                ret = mIat.startListening(mRecognizerListener);
                ToastUtil.showToast("开始识别");
                if (ret != ErrorCode.SUCCESS) {
                    ToastUtil.showToast("识别失败,错误码：" + ret);
                }
                tvTitle.setVisibility(View.GONE);
                recycleview.setVisibility(View.GONE);
            }

            @Override
            public void noPermission() {

            }
        }, Manifest.permission.RECORD_AUDIO);
    }

    public class Voice {

        public ArrayList<WSBean> ws;

        public class WSBean {
            public ArrayList<CWBean> cw;
        }

        public class CWBean {
            public String w;
        }
    }

    private class VoiceAdpater extends BaseQuickAdapter<VoiceBean, BaseViewHolder> {

        public VoiceAdpater(int layoutResId, @Nullable List<VoiceBean> data) {
            super(layoutResId, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, VoiceBean item) {

        }
    }

    private class Voice2Adpater extends BaseQuickAdapter<VoiceBean, BaseViewHolder> {

        public Voice2Adpater(int layoutResId, @Nullable List<VoiceBean> data) {
            super(layoutResId, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, VoiceBean item) {
            NoScrollView scrollView = helper.getView(R.id.gv_img);
            ArrayList<String> temp = new ArrayList<>();
            temp.add("");
            temp.add("");
            temp.add("");
            temp.add("");
            scrollView.setAdapter(new MyAdapter<String>(temp, R.layout.img) {

                @Override
                public void bindView(ViewHolder holder, String obj) {

                }
            });

        }
    }
}
